<?php

class Page_Main_Exception extends Page_Exception {}
class Page_Main_Invalid_Exception extends Page_Exception {}
class Page_Main_Not_Found_Exception extends Page_Exception {
	private $errors;
	public function __construct($errors){
		$this->errors = $errors;
	}

}

abstract class Page_Main {

	protected $parent;

	protected function __construct($data = array()){
		foreach((array) $data as $k => $v){
			$this->$k = $v;
		}
	}

	protected function URL($data){
		return $this->parent->URL($data, $this);
	}

	abstract function rid();

	public function run(){

	}

	public function output($child = null){
		$template = Output::getInstance()->Template(array('page','main'));
		if(isset($child)){
		        $template->module = $child;
		}
		return $template;
	}

	public static function Get($name, $parent){
		$pages = Page_Rewrite::Rewrite($name);
		$errors = array();

		foreach($pages as $page => $rewrite){
			try {
				$parts = explode('/', $page);
				$module = Module::Get($parts[0]);
				array_shift($parts);
				$class = $module->Load_Section('Page_Main');
				$parent->data_set($parts);
				$logic = call_user_func(array($class, 'Load'), $data = array(
					'rewrite' => $rewrite, 
					'parent' => $parent
				));
				if($logic instanceof Page_Main){
					return $logic;
				}
				throw new Page_Main_Invalid_Exception($logic);
			} catch (Exception $e){
				$errors[$page] = array($page, $rewrite,$e);
			}
		}
		throw new Page_Main_Not_Found_Exception($errors);
	}


}
